package com.gavinandre.socket;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ClientTarget implements Runnable{

	private Socket socket;


	public ClientTarget(Socket socket) {
		super();
		this.socket = socket;
	}

	@Override
	public void run() {
		//用于自动接收服务端发来的消息
		BufferedReader br = null;
		BufferedWriter bw = null;

		try {

			//创建用于写入聊天记录的字符缓冲输出流
			bw = new BufferedWriter(new FileWriter("D:\\qq\\talk.log", true));//追加

			//创建用于接收消息的字符输入流
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			while(true){
				String serverMsg = br.readLine();//获取服务端发来的消息
				System.out.println("服务端说："+serverMsg);

				mOnUpdataListener.upDataUI(serverMsg);

				//将从服务端收到的消息保存到聊天记录中
				bw.write("服务端说："+serverMsg);
				bw.newLine();
				bw.flush();

				if(serverMsg.equals("byebye too")){
					System.exit(0);//退出
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}





	private OnUpdataListener mOnUpdataListener;

	public void setOnUpdataListener(OnUpdataListener mOnUpdataListener) {
		this.mOnUpdataListener = mOnUpdataListener;
	}

	public interface OnUpdataListener {
		void upDataUI(String message);
	}


}
